<template>
  <div class="select-company-wrapper">
    <a-popover trigger="click" :visible="popoverVisible" @visibleChange="handleClickChange" placement="bottom">
      <div style="display: flex; align-items: center; cursor: pointer; min-height: 24px">
        <span class="font-title" @click="(e) => e.preventDefault()">{{ showSelect ? showSelect : companyName }}</span>
      </div>
      <div slot="content">
        <a-input-search style="width: 270px" class="mb8" placeholder="搜索关键字" :allowClear="true" @change="debouncedSearch" />
        <a-tree
          :showIcon="true"
          :treeData="dataList"
          :replaceFields="replaceFields"
          :expandedKeys="expandedKeys"
          :blockNode="true"
          style="max-width: 300px; max-height: 400px; overflow: auto"
          @expand="onExpand"
          @select="onSelect"
        >
          <a-icon slot="switcherIcon" type="down" />
          <div slot="custom" slot-scope="item">
            <div style="display: flex; align-items: center">
              <a-radio v-if="item.companyList === null" :checked="companyId === item.id" slot="icon" />
              <div style="flex: 1">
                <span v-html="item.name"></span>
              </div>
            </div>
          </div>
        </a-tree>
      </div>
    </a-popover>
  </div>
</template>

<script>
import { findCompanyGroupReq } from "./api";
import { mapState } from "vuex";
import _ from "lodash";
import { findAllParentIds } from "@/utils/tools";
export default {
  props: {
    showSelect: {
      type: String,
      default: undefined
    }
  },
  data() {
    return {
      replaceFields: {
        children: "companyList",
        title: "name",
        key: "id",
        value: "id"
      },
      popoverVisible: false, // popover显示状态
      dataList: [], // 树数据
      expandedKeys: []
    };
  },
  computed: {
    ...mapState(["hr"]),
    companyId() {
      return this.hr.companyId;
    },
    companyName() {
      return this.hr.companyName;
    }
  },
  created() {
    this.findCompanyGroup();
    this.debouncedSearch = _.debounce(this.onSearchChange, 1000);
  },
  methods: {
    onSearchChange(e) {
      this.findCompanyGroup(e.target.value);
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
    },
    handleClickChange(visible) {
      this.popoverVisible = visible;
    },
    // 选择树点击事件
    onSelect(selectedKeys, info) {
      if (selectedKeys.length === 0) {
        return;
      }

      if (info.node.dataRef.companyList) {
        const ind = this.expandedKeys.indexOf(selectedKeys[0]);
        if (ind !== -1) {
          this.expandedKeys.splice(ind, 1);
        } else {
          this.expandedKeys.push(selectedKeys[0]);
        }
        return;
      }

      const selectOne = info.node.dataRef;
      if (selectOne.type === "company") {
        const theCompany = {
          id: selectOne.id,
          name: selectOne.name.replace(new RegExp('<span style="color: #3C8AFF">', "g"), "").replace(new RegExp("</span>", "g"), "")
        };
        this.$store.dispatch("onCompanyClick", theCompany);
        this.$emit("selectCompany", theCompany);
      }

      this.popoverVisible = false;
    },
    // 查询所有组和用工单位
    findCompanyGroup(value) {
      findCompanyGroupReq({ name: value || undefined })
        .then((res) => {
          this.dataList = this.addTreeSlot(res.data);
          if (value) {
            this.expandedKeys = findAllParentIds(this.dataList);
          }

          this.dataList.map((item, index) => {
            this.dataList[index].name = this.ruleTitle(this.dataList[index].name, value);
            if (item.companyList) {
              item.companyList.map((item2, index2) => {
                this.dataList[index].companyList[index2].name = this.ruleTitle(this.dataList[index].companyList[index2].name, value);
              });
            }
          });
        })
        .catch((err) => {
          console.log("Company load error", err);
        });
    },
    ruleTitle(titleString, searchName) {
      if (!titleString || !searchName) {
        return titleString;
      }
      if (searchName && searchName.length > 0) {
        // 匹配关键字正则
        const replaceReg = new RegExp(searchName, "g");
        // 高亮替换v-html值
        const replaceString = '<span style="color: #3C8AFF">' + searchName + "</span>";
        // 开始替换
        titleString = titleString.replace(replaceReg, replaceString);
      }
      return titleString;
    },
    addTreeSlot(data) {
      // treeData添加字段
      if (!data) {
        return [];
      }
      data.forEach((el) => {
        el.scopedSlots = { title: "custom" };
        this.addTreeSlot(el.companyList);
      });
      return data;
    }
  }
};
</script>

<style lang="scss" scoped>
.select-company-wrapper {
  .iconfont {
    color: var(--primary);
  }
  .font-title {
    font-size: 16px;
    font-weight: 500;
    color: #55565d;
    line-height: 22px;
  }
}
</style>
